package QC.MessageBox.handler;

import QC.MessageBox.annotation.MethodLog;
import QC.MessageBox.annotation.RouteMapping;
import QC.MessageBox.beans.RedirectUrl;
import QC.MessageBox.beans.WXPublic;
import QC.MessageBox.beans.appmsg.ExtraMsg;
import QC.MessageBox.beans.rcform.RCSingleForm;
import QC.MessageBox.beans.wbmsg.WBTextMsg;
import QC.MessageBox.beans.wxmsg.media.Article;
import QC.MessageBox.beans.wxmsg.media.MPNews;
import QC.MessageBox.beans.wxmsg.normalmsg.WXGroupSendByList;
import QC.MessageBox.common.Constants;
import QC.MessageBox.service.*;
import io.vertx.core.CompositeFuture;
import io.vertx.core.Future;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.Json;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Created by Andaren on 2017/5/9.
 * Used for:
 */
@RouteMapping(path = "/test")
public class TestHandler extends HandlerBase {

    private BlockingService blockingService;

    private static final Logger LOGGER = LoggerFactory.getLogger(TestHandler.class);

    public TestHandler () {

    }

    public TestHandler (Map<String, Object> handlerMap) {
        Objects.requireNonNull(handlerMap);
        this.dataAccess = (DataAccess)handlerMap.get("dataAccess");
        this.httpService = (HttpService)handlerMap.get("httpService");
        this.sqlService = (MySQLService)handlerMap.get("mySQLService");
        this.redisService = (RedisService)handlerMap.get("redisService");
//        this.mongoService = (MongoService) handlerMap.get("mongoService");
        this.webClientService = (WebClientService)handlerMap.get("webClientService");
        this.blockingService = (BlockingService)handlerMap.get("blockingService");
    }

    /**
     * 测试：从中间件发送消息到融云（转到app）
     * @param routingContext
     */
    @RouteMapping(path = "/rc/message/send/")
    @MethodLog("（测试）发送一则消息至融云")
    public void appTestSendMSG(RoutingContext routingContext) {
        HttpServerRequest request = routingContext.request();
        HttpServerResponse response = routingContext.response();
        response
                .putHeader("content-type", "text/json")
                .end(Constants.successResult());

        String msgStr = routingContext.getBodyAsString();
        ExtraMsg extraMsg = new ExtraMsg();
        extraMsg.setDeveloperId("gh_0ddb7b0febec")
                .setHeadUrl("http://www.rongcloud.cn/images/logo.png")
                .setNickName("我是一个融云")
                .setOpenId("oVLnEuNCguqEpx_SUqY37aB6CGbQ")
                .setPublicName("全诚科技")
                .setType("wx")
                .setTimestamp("1409304348");
        JsonObject msgJson = new JsonObject()
                .put("content", msgStr)
                .put("extra", Json.encode(extraMsg));
        RCSingleForm singleForm = new RCSingleForm()
                .setFromUserId("7420688240")
                .setToUserId("5105681061")
                .setObjectName("RC:TxtMsg")
                .setContent(msgJson.encodePrettily());

        httpService.postSingleMsg(singleForm).setHandler(as -> {
            if (as.succeeded()) {
                System.out.println("融云发送消息完成");
            } else {
                LOGGER.info("融云接口发送消息失败：" + as.cause().getMessage());
            }
        });
    }

    /**
     * 切换 融云生产环境/测试环境
     * @param context
     */
    @RouteMapping(path = "/rc/switch/:type")
    @MethodLog("切换 融云生产环境/测试环境")
    public void switchRCConnection(RoutingContext context) {
        HttpServerRequest request = context.request();
        HttpServerResponse response = context.response();
        response
                .putHeader("content-type", "text/json")
                .end(Constants.successResult());
        String type = request.getParam("type");
        if ("test".equals(type)) {
            HttpService.RC_ISTEST = true;
        } else if ("production".equals(type)) {
            HttpService.RC_ISTEST = false;
        }
    }

    /**
     * 切换 App后台生产环境/测试环境
     * @param context
     */
    @RouteMapping(path = "/app/switch/:type")
    @MethodLog("改变app后台请求")
    public void switchAppBackgorundConnection(RoutingContext context) {
        HttpServerRequest request = context.request();
        HttpServerResponse response = context.response();
        response
                .putHeader("content-type", "text/json")
                .end(Constants.successResult());
        String type = request.getParam("type");
        if ("test".equals(type)) {
            HttpService.APPBACK_ISTEST = true;
        } else if ("production".equals(type)) {
            HttpService.APPBACK_ISTEST = false;
        }
    }

    @RouteMapping(path = "/update/token/")
    @MethodLog("（测试）更新token")
    public void updateTokenInTest(RoutingContext context) {
        HttpServerResponse response = context.response();
        response.end("ok");
        updateAccessTokenByAll();
    }

    @RouteMapping(path = "/route")
    @MethodLog("测试路径映射")
    public void testRouteMapping(RoutingContext context) {
        HttpServerRequest request = context.request();
        HttpServerResponse response = context.response();
        response
                .end("ok");
        sqlService.testFut();
    }

//    @RouteMapping(path = "/groupsend")
//    @MethodLog("测试群发")
    public void groupSendMsg(RoutingContext context) {
        HttpServerRequest request = context.request();
        HttpServerResponse response = context.response();

        String sourceurl = request.getParam("sourceurl");
        sourceurl = "http://www.quanzilife.cn/index.php?g=Wap&m=Index&a=content&token=hzmndo1454489422&id=885";
        final RedirectUrl redirectUrl = new RedirectUrl();
        redirectUrl
                .setRedirectUrl(sourceurl)
                .setState("STATE");

        final List<String> openIdList = new ArrayList<>();
        openIdList.add("oVLnEuDtsa36n8QcDxvDfeXywoS8");
        openIdList.add("oVLnEuNCguqEpx_SUqY37aB6CGbQ");
        openIdList.add("oVLnEuAW8Or24M7Xa_Kqew-Rpr9M");
        // 图文消息封面图的媒体资源ID
        final String thumbMedia = "http://wx.qlogo.cn/mmopen/WAibKjHvK5nFwbIZtjYdKjsAHOVxJicD49pmgBNmxqjddMgGT0Ft4dRKxVYoDYu28wibsSGgO1ahibztM40dMksczlAc45OzOfYk/0";
        // 图文消息中的图片的媒体资源ID
        final String imageUrl = "http://mmbiz.qpic.cn/mmbiz_jpg/thr6icdLqafpMJkgCC9aCc6Dw29ibthIWjplsnXICicolp9Sny16LEibkYmFlMRtXNHVbzhAoQJH9B3UoM6x1mc1LQ/0";

//        String defaultMediaId = "XPwEqceAY4KFhIWBdzfFG7r5M6Ccrkz7Qh5kY68ZctIDfiKLowQwchnWcrNBGjsL";

        Future<Void> groupSendfut = Future.future();
        final String developerId = "gh_0ddb7b0febec";
        getAccessTokenIfExpired(developerId)
                .compose(token -> {
                    Future<String> mediaUrlFut = Future.future();
                    blockingService.createFileFromUrl(imageUrl)
                            .compose(fileRes ->
                                    httpService.uploadImageWhenGroupSend(token, fileRes)
                            )
                            .compose(url ->
                                            mediaUrlFut.complete(url),
                                    mediaUrlFut);
//
                    Future<String> thumbPicMedia = Future.future();
//                    thumbPicMedia.complete(defaultMediaId);
                    blockingService.createFileFromUrl(thumbMedia)
                            .compose(fileRes ->
                                            /**
                                             * 群发图文时，上传的图文缩略图时临时素材而不是永久素材
                                             */
//                                    httpService.uploadPermanentMedia(token, fileRes, "image")
                                      httpService.getMediaIdByPostMediaToWX(token, "thumb", fileRes)
//                                    blockingService.synUploadPermanentMediaByHttpClient4(token, fileRes, "thumb")
                            )
                            .compose(mediaId ->
                                            thumbPicMedia.complete(mediaId),
                                    thumbPicMedia);
                    CompositeFuture.all(mediaUrlFut, thumbPicMedia)
//                    thumbPicMedia
                            .compose(compositeFutureAr -> {
                                String picInMsgMediaId = compositeFutureAr.resultAt(0);
                                String thumbPicMediaId = compositeFutureAr.resultAt(1);
//                                String picInMsgMediaId = compositeFutureAr;
                                MPNews mpNews = new MPNews();
                                Article article = new Article();
                                article.setAuthor("Andaren")
                                        .setContent("这是一个测试的群发图文消息\n " + "<img src='"+picInMsgMediaId+"'/>")
                                        .setContent_source_url(redirectUrl.getRedirectUrl())
                                        .setShow_cover_pic(1)
                                        .setTitle("测试的群发图文消息")
                                        .setThumb_media_id(thumbPicMediaId) // thumbPicMediaId)
                                        .setDigest("摘要");
                                List<Article> articles = new ArrayList<>();
                                articles.add(article);
                                mpNews.setArticleList(articles);
                                return webClientService.uploadMPNews(token, mpNews);
                            })
                            .compose(mediaId -> {
                                WXGroupSendByList groupSendByList = new WXGroupSendByList();
                                groupSendByList.setOpenIdList(openIdList)
                                        .setSendIgnoreReprint(0)
                                        .setMediaId(mediaId)
                                        .setMsgType("mpnews");
                                return webClientService.wxMsgGroupSendByList(token, groupSendByList);
                            })
                            .compose(mpnewsRetAr -> {
                                response
                                        .end(">>>>>>>>>>>>>>>>>>>>>>>>群发完成！<<<<<<<<<<<<<<<<<<<<<<<<<");
                                groupSendfut.complete();
                            }, groupSendfut);
                }, groupSendfut);

        commonEndFuture(groupSendfut, "群发图文", LOGGER);
    }

//    @RouteMapping(path = "/upload/video", method = HttpMethod.GET)
//    @MethodLog("测试上传视频")
    public void testPost(RoutingContext context) {
        HttpServerRequest request = context.request();
        HttpServerResponse response = context.response();
        String path = "D:\\Andaren\\SVN-Pro\\MessageBox\\20140619_002720.mp4";
        File video = new File(path);
        List<String> openIdList = new ArrayList<>();
        openIdList.add("oVLnEuDtsa36n8QcDxvDfeXywoS8");
        openIdList.add("oVLnEuH7dDWqKVtI5FCCXC58On50");
        openIdList.add("oVLnEuAW8Or24M7Xa_Kqew-Rpr9M");
        Future fut = Future.future();
        dataAccess.getWXPublicInfoByDeveloperId("gh_0ddb7b0febec")
                .compose(wxPublic -> {
                    httpService.getMediaIdByPostMediaToWX(wxPublic.getAccessToken(), "video", video)
                            .compose(media ->
                                webClientService.exchangeMediaId(wxPublic.getAccessToken(), media)
                            )
                            .compose(realMediaId -> {
                                System.out.println(realMediaId);
                                WXGroupSendByList groupSendByList = new WXGroupSendByList();
                                groupSendByList.setOpenIdList(openIdList)
                                        .setSendIgnoreReprint(0)
                                        .setMediaId(realMediaId)
                                        .setMsgType("mpvideo");
                                System.out.println(Json.encodePrettily(groupSendByList));
                                return webClientService.wxMsgGroupSendByList(wxPublic.getAccessToken(), groupSendByList);
                            })
                            .compose(mpvedioRetAr -> {
                                fut.complete(mpvedioRetAr);
                                response.end(mpvedioRetAr);
                            }, fut);
                }, fut);
    }

//    @RouteMapping(path = "/delete/all/:name")
//    @MethodLog("删除清空据库中所有数据和redis中所有缓存内容")
    public void deleteTestContext(RoutingContext context) {
        HttpServerRequest request = context.request();
        HttpServerResponse response = context.response();
        String name = request.getParam("name");
        if ("Andaren".equals(name)) {
            sqlService.deleteAllContentInTableForClearData();
            redisService.deleteAllKey();
        } else {
            response.end("你没有该权限,请联系开发人员.");
        }
    }

    @RouteMapping(path = "/wb/pullFans")
    @MethodLog("微博拉粉")
    public void testPullWBFans(RoutingContext context) {
        context.response().end("ok");
        WXPublic pub = new WXPublic();
        pub.setChannelType(1)
                .setAccessToken("2.00nmlaMGN1P5UCc818212767nBEeCC")
                .setName("圈子你我微博平台")
                .setDeveloperId("5682876525");
        pullFansFromWB(pub);
    }

    @RouteMapping(path = "/wb/reply")
    @MethodLog("微博回复")
    public void testWBSend(RoutingContext context) {
        context.response().end("ok");
        WBTextMsg wbMsg = new WBTextMsg();
        wbMsg.setReceiver_id(2146666360L)
                .setData(new JsonObject().put("text", "测试消息").encode())
                .setAccess_token("2.00nmlaMGN1P5UCc818212767nBEeCC")
                .setType("text");
        webClientService.sendMsgToFans("2.00nmlaMGN1P5UCc818212767nBEeCC", wbMsg);
    }

    @RouteMapping(path = "/url/title")
    @MethodLog("获取标题")
    public void testGetTitleFromUrl(RoutingContext context) {
        Future<Void> fut = Future.future();
        blockingService.getTitleFromURL("http://www.157buy.com")
                .compose(title -> {
                    System.out.println(title);
                    fut.complete();
                }, fut);
    }

    @RouteMapping(path = "/:name/test/route")
    @MethodLog("web talk handler")
    public void emptyKKTest (RoutingContext context) {
        HttpServerRequest request = context.request();
        HttpServerResponse response = context.response();
        String name = request.getParam("name");

        System.out.println("Test********************");
        System.out.println("name->" + name);
        response.end(name);
    }


}
